/**
 * 连接管理器 - 统一管理HTTP和WebSocket连接状态
 * 替代分散的连接状态检查逻辑
 */
import appStateManager from './app-state-manager.js'

class ConnectionManager {
  constructor() {
    this.connections = {
      http: { 
        status: 'disconnected', 
        lastCheck: null,
        retryCount: 0
      },
      websocket: { 
        status: 'disconnected', 
        lastCheck: null,
        retryCount: 0
      }
    }
    
    this.callbacks = []
    this.wsService = null
    this.maxRetries = 3
    this.retryDelay = 2000
    
    console.log('连接管理器初始化完成')
  }

  // 设置WebSocket服务引用
  setWebSocketService(wsService) {
    this.wsService = wsService
    console.log('WebSocket服务已注册到连接管理器')
    
    // 监听WebSocket状态变化
    if (wsService && wsService.onStatusChange) {
      wsService.onStatusChange((statusInfo) => {
        this.handleWebSocketStatusChange(statusInfo)
      })
    }
  }

  // 处理WebSocket状态变化
  handleWebSocketStatusChange(statusInfo) {
    let wsStatus = 'disconnected'
    
    if (statusInfo.status === 'connected') {
      wsStatus = 'connected'
    } else if (statusInfo.status === 'reconnecting') {
      wsStatus = 'reconnecting'
    } else if (statusInfo.status === 'error') {
      wsStatus = 'error'
    }

    this.updateConnection('websocket', {
      status: wsStatus,
      lastCheck: new Date(),
      retryCount: statusInfo.status === 'connected' ? 0 : this.connections.websocket.retryCount
    })

    // 同步更新应用状态管理器
    appStateManager.updateChatConnectionStatus(
      wsStatus === 'connected',
      this.connections.websocket.retryCount
    )
  }

  // 启动连接管理
  start() {
    console.log('启动连接管理器...')
    
    // 订阅应用状态管理器的服务器状态
    appStateManager.subscribe('server', (serverState) => {
      this.updateConnection('http', {
        status: serverState.isOnline ? 'connected' : 'disconnected',
        lastCheck: serverState.lastCheck,
        retryCount: serverState.isOnline ? 0 : this.connections.http.retryCount + 1
      })
    })

    // 初始状态检查
    this.checkAllConnections()
  }

  // 检查所有连接状态
  async checkAllConnections() {
    console.log('检查所有连接状态...')
    
    // HTTP连接检查（通过应用状态管理器）
    const isServerOnline = await appStateManager.checkServerHealth()
    
    // WebSocket连接检查
    const isWSConnected = this.wsService ? this.wsService.isConnected : false
    
    this.updateConnection('http', {
      status: isServerOnline ? 'connected' : 'disconnected',
      lastCheck: new Date()
    })

    this.updateConnection('websocket', {
      status: isWSConnected ? 'connected' : 'disconnected',
      lastCheck: new Date()
    })

    this.notifyCallbacks()
    
    console.log('连接状态检查完成:', {
      http: this.connections.http.status,
      websocket: this.connections.websocket.status
    })
  }

  // 更新连接状态
  updateConnection(connectionType, updates) {
    const oldStatus = this.connections[connectionType].status
    this.connections[connectionType] = {
      ...this.connections[connectionType],
      ...updates
    }

    // 如果状态发生变化，记录日志
    if (oldStatus !== this.connections[connectionType].status) {
      console.log(`${connectionType}连接状态变化: ${oldStatus} -> ${this.connections[connectionType].status}`)
    }

    this.notifyCallbacks()
  }

  // 订阅连接状态变化
  subscribe(callback) {
    this.callbacks.push(callback)
    
    // 立即返回当前状态
    callback(this.connections)
    
    console.log(`新增连接状态订阅，当前订阅数: ${this.callbacks.length}`)
  }

  // 取消订阅
  unsubscribe(callback) {
    const index = this.callbacks.indexOf(callback)
    if (index > -1) {
      this.callbacks.splice(index, 1)
      console.log('移除连接状态订阅')
    }
  }

  // 通知所有订阅者
  notifyCallbacks() {
    this.callbacks.forEach(callback => {
      try {
        callback(this.connections)
      } catch (error) {
        console.error('连接状态回调执行失败:', error)
      }
    })
  }

  // 重试HTTP连接
  async retryHttpConnection() {
    if (this.connections.http.retryCount >= this.maxRetries) {
      console.log('HTTP连接重试次数已达上限')
      return false
    }

    console.log(`重试HTTP连接 (${this.connections.http.retryCount + 1}/${this.maxRetries})`)
    
    this.updateConnection('http', {
      status: 'reconnecting',
      retryCount: this.connections.http.retryCount + 1
    })

    // 延迟后重试
    await new Promise(resolve => setTimeout(resolve, this.retryDelay))
    
    const isOnline = await appStateManager.checkServerHealth()
    return isOnline
  }

  // 重试WebSocket连接
  async retryWebSocketConnection() {
    if (!this.wsService) {
      console.log('WebSocket服务未注册，无法重试')
      return false
    }

    if (this.connections.websocket.retryCount >= this.maxRetries) {
      console.log('WebSocket连接重试次数已达上限')
      return false
    }

    console.log(`重试WebSocket连接 (${this.connections.websocket.retryCount + 1}/${this.maxRetries})`)
    
    this.updateConnection('websocket', {
      status: 'reconnecting',
      retryCount: this.connections.websocket.retryCount + 1
    })

    try {
      await this.wsService.init()
      return this.wsService.isConnected
    } catch (error) {
      console.error('WebSocket重连失败:', error)
      return false
    }
  }

  // 重置重试计数
  resetRetryCount(connectionType) {
    this.updateConnection(connectionType, { retryCount: 0 })
  }

  // 获取连接状态
  getConnectionStatus(connectionType = null) {
    if (connectionType) {
      return this.connections[connectionType]
    }
    return this.connections
  }

  // 检查是否所有连接都正常
  isAllConnected() {
    return this.connections.http.status === 'connected' && 
           this.connections.websocket.status === 'connected'
  }

  // 检查是否有连接正常
  hasAnyConnection() {
    return this.connections.http.status === 'connected' || 
           this.connections.websocket.status === 'connected'
  }

  // 获取连接状态摘要
  getConnectionSummary() {
    const httpOk = this.connections.http.status === 'connected'
    const wsOk = this.connections.websocket.status === 'connected'
    
    if (httpOk && wsOk) {
      return { status: 'excellent', message: '所有连接正常' }
    } else if (httpOk || wsOk) {
      return { status: 'partial', message: '部分连接可用' }
    } else {
      return { status: 'offline', message: '连接不可用' }
    }
  }

  // 手动刷新所有连接状态
  async refresh() {
    console.log('手动刷新连接状态...')
    await this.checkAllConnections()
    return this.connections
  }

  // 销毁连接管理器
  destroy() {
    this.callbacks = []
    this.wsService = null
    console.log('连接管理器已销毁')
  }
}

// 创建全局单例
const connectionManager = new ConnectionManager()

// 导出单例
export default connectionManager 